package com.licheedev.myutils

import com.google.gson.reflect.TypeToken

/**
 * 任何对象序列化为json字符串
 * @receiver Any? 如果对象为null，返回""(即空字符串)
 * @return String
 */
fun Any?.toJson(): String {
    if (this == null) {
        return ""
    }
    return GsonUtil.toJson(this)
}

/**
 * 任何对象序列化为json字符串
 * @receiver Any? 如果对象为null，返回null
 * @return String
 */
fun Any?.toJsonOrNull(): String? {
    if (this == null) {
        return null
    }
    return GsonUtil.toJson(this)
}

/**
 * 任何对象序列化为json字符串
 * @receiver Any? 如果对象为null，返回"{}"
 * @return String
 */
fun Any?.toJsonOrDefault(): String {
    if (this == null) {
        return "{}"
    }
    return GsonUtil.toJson(this)
}

/** 解释json到对象 */
inline fun <reified T> String.toObject(): T? {
    return GsonUtil.toObject(this, T::class.java)
}

/** 解释json到数组 */
inline fun <reified T> String.toList(): List<T> {
    val type = object : TypeToken<List<T>>() {}.type
    return GsonUtil.toList(this, type)
}

/** 解释json到泛型对象 */
inline fun <reified T> String.toGenericObject(): T? {
    val type = object : TypeToken<T>() {}.type
    return GsonUtil.toObject(this, type)
}

/** 获取泛型类型 */
inline fun <reified T> genericType() = object : TypeToken<T>() {}.type

/**
 * 从文本中抽出多个json字符串
 */
fun String?.extractJson(): List<String> {
    if (this == null) {
        return listOf()
    }

    var start = 0
    var leftAmount = 0
    var rightAmount = 0

    val result = mutableListOf<String>()

    this.forEachIndexed { index, c ->
        when (c) {
            '{' -> {
                if (leftAmount == 0) {
                    start = index
                }
                leftAmount++
            }
            '}' -> {
                rightAmount++
                if (rightAmount == leftAmount) {
                    result.add(this.substring(start, index + 1))
                    // 重置计数
                    start = 0
                    leftAmount = 0
                    rightAmount = 0
                }
            }
        }
    }
    return result
}



